﻿Imports System.Security.Cryptography.X509Certificates

Public Class frmSelectCertificateFile

    Public Property selectedSigningCertificate As X509Certificate2 = Nothing

    Private Sub cmdOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOK.Click
        Try
            If rbCER.Checked Then
                If IO.File.Exists(fldCERFile.Text) Then
                    selectedSigningCertificate = X509Certificate2.CreateFromCertFile(fldCERFile.Text)
                Else
                    MsgBox("Couldn't find the specified CER file!", MsgBoxStyle.Critical, "Error")
                End If
            Else
                Dim cert As Byte()
                If IO.File.Exists(fldPFXFile.Text) Then
                    cert = IO.File.ReadAllBytes(fldPFXFile.Text)
                    If Not String.IsNullOrEmpty(Me.fldPFXPassword.Text.Trim) Then
                        selectedSigningCertificate = New X509Certificate2(cert, Me.fldPFXPassword.Text)
                    Else
                        selectedSigningCertificate = New X509Certificate2(cert)
                    End If
                Else
                    MsgBox("Couldn't find the specified PFX file!", MsgBoxStyle.Critical, "Error")
                End If
            End If
        Catch ex As Exception
            'TODO: catch certificate related exceptions and change the display message
            MsgBox("Error reading the specified certificate")
        End Try
    End Sub

    Private Sub rbPFX_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbPFX.CheckedChanged
        Me.PFXFileGroupBox.Enabled = rbPFX.Checked
    End Sub

    Private Sub rbCER_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbCER.CheckedChanged
        Me.CERFileGroupBox.Enabled = rbCER.Checked
    End Sub

    Private Sub cmdSelectPFXFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSelectPFXFile.Click
        Dim openFileDlg As New OpenFileDialog With {.Title = "Select a PFX file", .Filter = "PFX Certificate|*.pfx"}
        If openFileDlg.ShowDialog = DialogResult.OK Then
            Me.fldPFXFile.Text = openFileDlg.FileName
        End If
    End Sub

    Private Sub cmdSelectCERFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSelectCERFile.Click
        Dim openFileDlg As New OpenFileDialog With {.Title = "Select a CER file", .Filter = "CER Certificate|*.cer"}
        If openFileDlg.ShowDialog = DialogResult.OK Then
            Me.fldCERFile.Text = openFileDlg.FileName
        End If
    End Sub
End Class